package com.iknight.mgr.core.utils;

import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.ehcache.EhCacheCacheManager;

public class SpringEhcacheUtils {
	private EhCacheCacheManager ehcacheMgr;

	public EhCacheCacheManager getEhcacheMgr() {
		return ehcacheMgr;
	}

	public void setEhcacheMgr(EhCacheCacheManager ehcacheMgr) {
		this.ehcacheMgr = ehcacheMgr;
	}

	public Cache getCache(String cacheName) {
		Cache cache = ehcacheMgr.getCache(cacheName);
		if (cache == null) {
			throw new RuntimeException("根据cacheName=" + cacheName + "无法获取到对于的cache!请检查配置文件");
		}
		return cache;
	}

	public void put(String cacheName, String key, Object value) {
		Cache cache = getCache(cacheName);
		cache.put(key, value);
	}

	public Object get(String cacheName, String key) {
		Cache cache = ehcacheMgr.getCache(cacheName);
		ValueWrapper value = cache.get(key);
		return value == null ? "" : value.get();
	}

	public void remove(String cacheName, String key) {
		Cache cache = ehcacheMgr.getCache(cacheName);
		cache.clear();
	}
}
